<?php

class NetellerAccountController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'addAccount','getAccounts','updateLink','updateAccInfo','updateWorking','getMachineAccounts'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * 0 or null means initial save, 1 tried to signup and 2 for signup done, 3 means block.
     */
    public function actionAddAccount() {
        $response = "<Response>";
        if (!isset($_POST['request'])) {
            $response = $response . "<errorcode>000</errorcode><message>Request paramater is not found.</message></Response>";
            echo $response;
            return;
        }
        $request = $_POST['request'];

        $xml = simplexml_load_string($request);
        $username = $xml->username;
        $password = $xml->password;

        $errorMsg = $this->netellerAuthenticate($username, $password);
        if ($errorMsg != "") {
            $response = $response . "<errorcode>000</errorcode><message>" . $errorMsg . "</message></Response>";
            echo $response;
            return;
        }

        $record = NetellerUser::model()->findByAttributes(array('username' => $username));

        $model = new NetellerAccount;
        $model->user_id = $record->id;
        $model->email = $xml->email;
        $model->email_pass = $xml->email_pass;
        $model->fw_email = $xml->fw_email;
        $model->fw_email_pass = $xml->fw_email_pass;
        $model->serial = $xml->serial;
        $model->first_name = $xml->first_name;
        $model->last_name = $xml->last_name;
        $model->street = $xml->street;
        $model->city = $xml->city;        
        $model->region = $xml->region;
        $model->postcode = $xml->postcode;
        $model->phone = $xml->phone;
        $model->sex = $xml->sex;
        $model->day = $xml->day;
        $model->month = $xml->month;
        $model->year = $xml->year;
        $model->passport_no = $xml->passport_no;
        $model->verification = $xml->verification;   
        $model->remarks = $xml->remarks;
        $model->link = $xml->link;
        $model->working = $xml->working;
        $model->last_posted_date = date("Y-m-d H:i:s");
        if ($model->save()) {
            $response = $response . "<errorcode>001</errorcode><message>CL account has been created successfully.</message></Response>";
        } else {
            $response = $response . "<errorcode>000</errorcode><message>Problem in cl account creation. Please contact with system administrator</message></Response>";
        }
        echo $response;
        //print_r($xml);
    }
    
    public function actionUpdateWorking() {
        $response = "<Response>";
        if (!isset($_POST['request'])) {
            $response = $response . "<errorcode>000</errorcode><message>Request paramater is not found.</message></Response>";
            echo $response;
            return;
        }
        $request = $_POST['request'];

        $xml = simplexml_load_string($request);
        $username = $xml->username;
        $password = $xml->password;
        $id = $xml->id;
        $working = $xml->working;
        $errorMsg = $this->netellerAuthenticate($username, $password);
        if ($errorMsg != "") {
            $response = $response . "<errorcode>000</errorcode><message>" . $errorMsg . "</message></Response>";
            echo $response;
            return;
        }

        $model = NetellerAccount::model()->findByPK($id);
        $model->working = $working;
        if ($model->update()) {
            $response = $response . "<errorcode>001</errorcode><message>Updated successfully.</message></Response>";
        } else {
            $response = $response . "<errorcode>000</errorcode><message>Problem in account update. Please contact with system administrator</message></Response>";
        }
        echo $response;
    }
    
    public function actionGetAccounts($username, $password, $working) {
        $response = "<Response>";
        $errorMsg = $this->netellerAuthenticate($username, $password);
        if ($errorMsg != "") {
            $response = $response . "<errorcode>000</errorcode><message>" . $errorMsg . "</message></Response>";
            echo $response;
            return;
        }

        $record = NetellerUser::model()->findByAttributes(array('username' => $username));
        $list = NetellerAccount::model()->findAll("user_id=:user and working=:working", array("user" => $record->id, "working" => $working));

        $childRes = "<accounts>";
        foreach ($list as $account) {
            $childRes = $childRes . "<account>";
            $childRes = $childRes . "<id>" . $account->id . "</id>";
            $childRes = $childRes . "<user_id>" . $account->user_id . "</user_id>";
            $childRes = $childRes . "<email>" . $account->email . "</email>";
            $childRes = $childRes . "<email_pass>" . $account->email_pass . "</email_pass>";
            $childRes = $childRes . "<fw_email>" . $account->fw_email . "</fw_email>";
            $childRes = $childRes . "<fw_email_pass>" . $account->fw_email_pass . "</fw_email_pass>";
            $childRes = $childRes . "<serial>" . $account->serial . "</serial>";
            $childRes = $childRes . "<first_name>" . $account->first_name . "</first_name>";
            $childRes = $childRes . "<last_name>" . $account->last_name . "</last_name>";
            $childRes = $childRes . "<street>" . $account->street . "</street>";
            $childRes = $childRes . "<city>" . $account->city . "</city>";
            $childRes = $childRes . "<region>" . $account->region . "</region>";
            $childRes = $childRes . "<postcode>" . $account->postcode . "</postcode>";
            $childRes = $childRes . "<phone>" . $account->phone . "</phone>";
            $childRes = $childRes . "<sex>" . $account->sex . "</sex>";
            $childRes = $childRes . "<day>" . $account->day . "</day>";
            $childRes = $childRes . "<month>" . $account->month . "</month>";            
            $childRes = $childRes . "<year>" . $account->year . "</year>";
            $childRes = $childRes . "<passport_no>" . $account->passport_no . "</passport_no>";
            $childRes = $childRes . "<verification>" . $account->month . "</verification>";
            $childRes = $childRes . "<link>" . htmlspecialchars($account->link , ENT_QUOTES). "</link>";
            $childRes = $childRes . "<serial>" . $account->serial. "</serial>";
            $childRes = $childRes . "</account>";
        }
        $childRes = $childRes . "</accounts>";

        $response = $response . "<errorcode>001</errorcode><message>Record found</message>";
        $response = $response . $childRes . "</Response>";
        echo $response;
    }
    
    public function actionGetMachineAccounts($username, $password, $machine) {
        $response = "<Response>";
        $errorMsg = $this->netellerAuthenticate($username, $password);
        if ($errorMsg != "") {
            $response = $response . "<errorcode>000</errorcode><message>" . $errorMsg . "</message></Response>";
            echo $response;
            return;
        }
        $record = NetellerUser::model()->findByAttributes(array('username' => $username));
        $list = NetellerAccount::model()->findAll("user_id=:user and proxy like :mac", array("user" => $record->id, "mac" => $machine));

        $childRes = "<accounts>";
        foreach ($list as $account) {
            $childRes = $childRes . "<account>";
            $childRes = $childRes . "<id>" . $account->id . "</id>";
            $childRes = $childRes . "<user_id>" . $account->user_id . "</user_id>";
            $childRes = $childRes . "<email>" . $account->email . "</email>";
            $childRes = $childRes . "<email_pass>" . $account->email_pass . "</email_pass>";
            $childRes = $childRes . "<fw_email>" . $account->fw_email . "</fw_email>";
            $childRes = $childRes . "<fw_email_pass>" . $account->fw_email_pass . "</fw_email_pass>";
            $childRes = $childRes . "<serial>" . $account->serial . "</serial>";
            $childRes = $childRes . "<first_name>" . $account->first_name . "</first_name>";
            $childRes = $childRes . "<last_name>" . $account->last_name . "</last_name>";
            $childRes = $childRes . "<username>" . $account->username . "</username>";
            $childRes = $childRes . "<password>" . $account->password . "</password>";            
            $childRes = $childRes . "</account>";
        }
        $childRes = $childRes . "</accounts>";

        $response = $response . "<errorcode>001</errorcode><message>Record found</message>";
        $response = $response . $childRes . "</Response>";
        echo $response;
    }
    
    public function actionUpdateLink() {
        $response = "<Response>";
        if (!isset($_POST['request'])) {
            $response = $response . "<errorcode>000</errorcode><message>Request paramater is not found.</message></Response>";
            echo $response;
            return;
        }
        $request = $_POST['request'];

        $xml = simplexml_load_string($request);
        $username = $xml->username;
        $password = $xml->password;
        $id = $xml->id;
        $working = $xml->working;
        $link = $xml->link;
        $errorMsg = $this->netellerAuthenticate($username, $password);
        if ($errorMsg != "") {
            $response = $response . "<errorcode>000</errorcode><message>" . $errorMsg . "</message></Response>";
            echo $response;
            return;
        }

        $model = NetellerAccount::model()->findByPK($id);
        $model->working = $working;
        $model->link = $link;
        if ($model->update()) {
            $response = $response . "<errorcode>001</errorcode><message>Updated successfully.</message></Response>";
        } else {
            $response = $response . "<errorcode>000</errorcode><message>Problem in account update. Please contact with system administrator</message></Response>";
        }
        echo $response;
    }
    
    public function actionUpdateAccInfo() {
        $response = "<Response>";
        if (!isset($_POST['request'])) {
            $response = $response . "<errorcode>000</errorcode><message>Request paramater is not found.</message></Response>";
            echo $response;
            return;
        }
        $request = $_POST['request'];

        $xml = simplexml_load_string($request);
        $username = $xml->username;
        $password = $xml->password;
        $id = $xml->id;
        $errorMsg = $this->netellerAuthenticate($username, $password);
        if ($errorMsg != "") {
            $response = $response . "<errorcode>000</errorcode><message>" . $errorMsg . "</message></Response>";
            echo $response;
            return;
        }

        $model = NetellerAccount::model()->findByPK($id);
        $model->working = $xml->working;
        $model->username = $xml->neteller_username;
        $model->password = $xml->neteller_password;
        $model->account_no = $xml->account_no;
        $model->security_no = $xml->security_no;        
        $model->security_question1 = $xml->security_question1;
        $model->security_question2 = $xml->security_question2;
        $model->security_question3 = $xml->security_question3;        
        $model->security_answer1 = $xml->security_answer1;
        $model->security_answer2 = $xml->security_answer2;
        $model->security_answer3 = $xml->security_answer3;
        $model->proxy = $xml->proxy;
        if ($model->update()) {
            $response = $response . "<errorcode>001</errorcode><message>Updated successfully.</message></Response>";
        } else {
            $response = $response . "<errorcode>000</errorcode><message>Problem in account update. Please contact with system administrator</message></Response>";
        }
        echo $response;
    }
    
    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new NetellerAccount;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['NetellerAccount'])) {
            $model->attributes = $_POST['NetellerAccount'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['NetellerAccount'])) {
            $model->attributes = $_POST['NetellerAccount'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('NetellerAccount');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new NetellerAccount('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['NetellerAccount']))
            $model->attributes = $_GET['NetellerAccount'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return NetellerAccount the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = NetellerAccount::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param NetellerAccount $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'neteller-account-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
